using System.Text.RegularExpressions;
using Godot;
using System;

namespace Box;

public partial class FileMenu : MenuButton
{
	const long OPEN_ID = 0;
	const long SAVE_ID = 1;
	const long EXPORT_ID = 2;
	const long CREATE_TASK_ID = 3;
	const long CREATE_ACTION_ID = 4;

	public ProcessTreeGraphEditor ProcessTreeGraphEditor;
	FileDialog SaveFileWindow;
	FileDialog OpenFileWindow;
	FileDialog ExportWindow;
	public CreateFileWindow CreateTaskFileWindow;
	public CreateFileWindow CreateActionFileWindow;



	// Called when the node enters the scene tree for the first time.
	public override void _Ready()
	{
		SaveFileWindow = GetNode<FileDialog>("SaveFileWindow");
		OpenFileWindow = GetNode<FileDialog>("OpenFileWindow");
		ExportWindow = GetNode<FileDialog>("ExportWindow");
		CreateTaskFileWindow = GetNode<CreateFileWindow>("CreateTaskFileWindow");
		CreateActionFileWindow = GetNode<CreateFileWindow>("CreateActionFileWindow");


		var popup_menu = GetPopup();
		popup_menu.IdPressed += _onPressedItem;

		SaveFileWindow.FileSelected += onSave;
		OpenFileWindow.FileSelected += onOpen;
		ExportWindow.FileSelected += onExport;
	}

	public void _onPressedItem(long id) {
		switch (id) {
			case OPEN_ID 	:{
				OpenFileWindow.Show();
			};break;
			case SAVE_ID 	: {
				SaveFileWindow.Show();
			}break;
			case EXPORT_ID 	: {
				ExportWindow.Show();
			}break;
			case CREATE_TASK_ID 	: {
				CreateTaskFileWindow.Show();
			}break;
			case CREATE_ACTION_ID 	: {
				CreateActionFileWindow.Show();
			}break;
		}
	}

	public void onSave(string path) {
		FileAccess file = FileAccess.Open(path,FileAccess.ModeFlags.WriteRead);
		file.StoreString(ProcessTreeEditorHelper.ToJson(ProcessTreeGraphEditor));
		file.Close();
	}

	public void onOpen(string path) {
		FileAccess file = FileAccess.Open(path,FileAccess.ModeFlags.ReadWrite);
		ProcessTreeEditorHelper.ReadJson(file.GetAsText(),ProcessTreeGraphEditor);
		file.Close();
	}

	public void onExport(string path) {
		FileAccess file = FileAccess.Open(path,FileAccess.ModeFlags.Read);
		if(file.IsOpen()) {
			string file_name_full = ExportWindow.CurrentFile;
			string file_name = file_name_full.Substr(0,file_name_full.Length - 3);
			string dir_path = ExportWindow.CurrentDir;
			string code = file.GetAsText();
			string namespace_name = "";

			var namespace_match = Regex.Match(code,"namespace ([a-zA-z_0-9\u002E]+)");

			if(namespace_match.Success) {
				namespace_name = namespace_match.Value;
			}
			
			FileAccess write_file = FileAccess.Open($"{dir_path}/{file_name}.pt.cs",FileAccess.ModeFlags.WriteRead);

			if(write_file.IsOpen()) {
				write_file.StoreString(ProcessTreeEditorHelper.GenerateCode(ProcessTreeGraphEditor.RootNode,namespace_name,file_name));

				write_file.Close();
			}
		}
	}
}
